from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from fastapi.encoders import jsonable_encoder

from app.db.database import get_db
from app.core.security import get_current_user, get_current_active_user
from app.schemas.campsite import Campsite, CampsiteBrief, CampsiteCreate, CampsiteUpdate, CampsiteImage, CampsiteFollow
from app.crud import campsite as campsite_crud

router = APIRouter()


@router.get("/", response_model=List[CampsiteBrief])
async def read_campsites(
    skip: int = 0,
    limit: int = 100,
    search: Optional[str] = None,
    lat: Optional[float] = None,
    lon: Optional[float] = None,
    distance: Optional[float] = None,
    db: Session = Depends(get_db)
):
    """获取营地列表"""
    campsites = campsite_crud.get_campsites(
        db, skip=skip, limit=limit, search=search,
        lat=lat, lon=lon, distance=distance
    )
    return campsites


@router.post("/", response_model=Campsite)
async def create_campsite(
    campsite: CampsiteCreate,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """创建营地（需要管理员权限）"""
    if not current_user.get("is_admin"):
        raise HTTPException(status_code=403, detail="只有管理员可以创建营地")
    
    return campsite_crud.create_campsite(db, campsite=campsite)


@router.get("/{campsite_id}", response_model=Campsite)
async def read_campsite(
    campsite_id: int,
    db: Session = Depends(get_db)
):
    """获取营地详情"""
    campsite = campsite_crud.get_campsite(db, campsite_id=campsite_id)
    if not campsite:
        raise HTTPException(status_code=404, detail="营地不存在")
    return campsite


@router.put("/{campsite_id}", response_model=Campsite)
async def update_campsite(
    campsite_id: int,
    campsite: CampsiteUpdate,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """更新营地信息（需要管理员权限）"""
    if not current_user.get("is_admin"):
        raise HTTPException(status_code=403, detail="只有管理员可以更新营地信息")
    
    db_campsite = campsite_crud.get_campsite(db, campsite_id=campsite_id)
    if not db_campsite:
        raise HTTPException(status_code=404, detail="营地不存在")
    
    updated_campsite = campsite_crud.update_campsite(db, campsite_id=campsite_id, campsite=campsite)
    return updated_campsite


@router.delete("/{campsite_id}", response_model=dict)
async def delete_campsite(
    campsite_id: int,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """删除营地（软删除，需要管理员权限）"""
    if not current_user.get("is_admin"):
        raise HTTPException(status_code=403, detail="只有管理员可以删除营地")
    
    db_campsite = campsite_crud.get_campsite(db, campsite_id=campsite_id)
    if not db_campsite:
        raise HTTPException(status_code=404, detail="营地不存在")
    
    campsite_crud.delete_campsite(db, campsite_id=campsite_id)
    return {"status": "success"}


@router.post("/{campsite_id}/images", response_model=CampsiteImage)
async def add_campsite_image(
    campsite_id: int,
    image: CampsiteImage,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """添加营地图片（需要管理员权限）"""
    if not current_user.get("is_admin"):
        raise HTTPException(status_code=403, detail="只有管理员可以添加营地图片")
    
    db_campsite = campsite_crud.get_campsite(db, campsite_id=campsite_id)
    if not db_campsite:
        raise HTTPException(status_code=404, detail="营地不存在")
    
    return campsite_crud.add_campsite_image(db, campsite_id=campsite_id, image=image)


@router.delete("/{campsite_id}/images/{image_id}", response_model=dict)
async def delete_campsite_image(
    campsite_id: int,
    image_id: int,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """删除营地图片（需要管理员权限）"""
    if not current_user.get("is_admin"):
        raise HTTPException(status_code=403, detail="只有管理员可以删除营地图片")
    
    result = campsite_crud.delete_campsite_image(db, campsite_id=campsite_id, image_id=image_id)
    if not result:
        raise HTTPException(status_code=404, detail="营地或图片不存在")
    
    return {"status": "success"}


@router.post("/{campsite_id}/follow", response_model=CampsiteFollow)
async def follow_campsite(
    campsite_id: int,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """关注营地"""
    db_campsite = campsite_crud.get_campsite(db, campsite_id=campsite_id)
    if not db_campsite:
        raise HTTPException(status_code=404, detail="营地不存在")
    
    follow = campsite_crud.follow_campsite(db, user_id=current_user["id"], campsite_id=campsite_id)
    return follow


@router.delete("/{campsite_id}/follow", response_model=dict)
async def unfollow_campsite(
    campsite_id: int,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """取消关注营地"""
    result = campsite_crud.unfollow_campsite(db, user_id=current_user["id"], campsite_id=campsite_id)
    if not result:
        raise HTTPException(status_code=404, detail="关注关系不存在")
    
    return {"status": "success"}


@router.get("/{campsite_id}/followers", response_model=List[CampsiteFollow])
async def get_campsite_followers(
    campsite_id: int,
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db)
):
    """获取营地的关注者列表"""
    db_campsite = campsite_crud.get_campsite(db, campsite_id=campsite_id)
    if not db_campsite:
        raise HTTPException(status_code=404, detail="营地不存在")
    
    followers = campsite_crud.get_campsite_followers(db, campsite_id=campsite_id, skip=skip, limit=limit)
    return followers


@router.get("/user/followed", response_model=List[CampsiteBrief])
async def get_followed_campsites(
    skip: int = 0,
    limit: int = 100,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取当前用户关注的营地列表"""
    campsites = campsite_crud.get_user_followed_campsites(db, user_id=current_user["id"], skip=skip, limit=limit)
    return campsites 